import { useState, Suspense } from 'react'
import { useParams } from 'react-router-dom'
import Loading from '@/components/Loading'
import {
  Dialog,
  DialogContent,
  DialogDescription,
  DialogHeader,
  DialogTitle,
  DialogTrigger
} from '@/components/ui/dialog'
import { Button } from '@/components/ui/button'

// 懒加载 MdViewer 组件 - 只在需要时加载整个 markdown 生态系统
// const MdViewer = lazy(() => import('@/components/ui/markdown-reader'))
import { MarkdownReader } from '@/components/ui/markdown-reader' // 直接导入已优化的 MdViewer

// Analysis 组件本身也支持懒加载导出
const AnalysisComponent = () => {
  const { id } = useParams<{ id: string }>()
  const [data, setData] = useState<string | null>(null)
  const [loading, setLoading] = useState<boolean>(false)
  const [error, setError] = useState<string | null>(null)

  const fetchData = async () => {
    setLoading(true)
    try {
      const response = await fetch(`/rpi/sun/ai/${id}`)
      if (!response.ok) {
        throw new Error('Network response was not ok')
      }
      const result = await response.json()
      setData(result)
    } catch (error) {
      setError((error as Error).message)
    } finally {
      setLoading(false)
    }
  }

  const handleButtonClick = () => {
    fetchData()
  }

  return (
    <div>
      <Dialog>
        <DialogTrigger asChild>
          <Button
            variant="ghost"
            size="sm"
            className="h-7 px-2 text-xs"
            onClick={handleButtonClick}
          >
            ai分析
          </Button>
        </DialogTrigger>
        <DialogContent className="max-h-[80vh] max-w-[80vh] overflow-y-auto">
          {loading ? (
            <div className="flex flex-col items-center justify-center py-8">
              <Loading />
              <div className="mt-4 text-center text-sm text-gray-600">
                <p className="mb-2">AI正在分析中，请耐心等待...</p>
                <p className="text-xs text-gray-500">
                  免费AI服务，响应时间较长，感谢理解 🤖
                </p>
              </div>
            </div>
          ) : error ? (
            <div>Error: {error}</div>
          ) : (
            <DialogHeader>
              <DialogTitle>AI 分析报告：</DialogTitle>
              <DialogDescription>
                {data ? (
                  <Suspense fallback={<div>加载分析报告...</div>}>
                    <MarkdownReader content={data} />
                  </Suspense>
                ) : (
                  'No content available'
                )}
              </DialogDescription>
            </DialogHeader>
          )}
        </DialogContent>
      </Dialog>
    </div>
  )
}

export default AnalysisComponent
